package models

import (
	"github.com/beego/beego/v2/client/orm"
)

// Franchise 加盟商模型
type Franchise struct {
	BaseModel
	Name        string `orm:"size(100)" json:"name"`
	Logo        string `orm:"size(255)" json:"logo"`
	Description string `orm:"size(500)" json:"description"`
	Contact     string `orm:"size(50)" json:"contact"`
	Phone       string `orm:"size(20)" json:"phone"`
	Email       string `orm:"size(100)" json:"email"`
	Address     string `orm:"size(255)" json:"address"`
	Status      int8   `orm:"default(1)" json:"status"` // 1:正常, 0:禁用
	ExpireAt    int64  `orm:"" json:"expire_at"`        // 合约到期时间
}

// TableName 设置表名
func (f *Franchise) TableName() string {
	return "ss_franchise"
}

// GetFranchiseById 根据ID获取加盟商信息
func GetFranchiseById(id int64) (*Franchise, error) {
	franchise := &Franchise{BaseModel: BaseModel{Id: id}}
	o := orm.NewOrm()
	err := o.Read(franchise)
	return franchise, err
}

// GetFranchiseList 获取加盟商列表
func GetFranchiseList(page, pageSize int, filters map[string]interface{}) ([]*Franchise, int64, error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(Franchise))

	// 应用过滤条件
	if name, ok := filters["name"].(string); ok && name != "" {
		qs = qs.Filter("name__contains", name)
	}

	if status, ok := filters["status"].(int8); ok {
		qs = qs.Filter("status", status)
	}
	if contact, ok := filters["contact"].(string); ok && contact != "" {
		qs = qs.Filter("contact__contains", contact)
	}
	if phone, ok := filters["phone"].(string); ok && phone != "" {
		qs = qs.Filter("phone__contains", phone)
	}

	// 排除已删除的记录
	qs = qs.Filter("is_deleted", 0)

	// 获取总数
	total, _ := qs.Count()

	// 分页查询
	var franchises []*Franchise
	_, err := qs.OrderBy("-id").Limit(pageSize, (page-1)*pageSize).All(&franchises)

	return franchises, total, err
}

// CreateFranchise 创建加盟商
func CreateFranchise(franchise *Franchise) (int64, error) {
	o := orm.NewOrm()
	id, err := o.Insert(franchise)
	return id, err
}

// UpdateFranchise 更新加盟商信息
func UpdateFranchise(franchise *Franchise, fields ...string) error {
	o := orm.NewOrm()
	_, err := o.Update(franchise, fields...)
	return err
}

// DeleteFranchise 删除加盟商（软删除）
func DeleteFranchise(id int64) error {
	o := orm.NewOrm()
	franchise := &Franchise{BaseModel: BaseModel{Id: id}}
	if err := o.Read(franchise); err != nil {
		return err
	}

	franchise.IsDeleted = 1
	_, err := o.Update(franchise, "IsDeleted")
	return err
}
